/*
	OpenGL Frambuffer Object (FBO) abstraction. Includes fp16 framebuffers

	MIT License

	Copyright (c) 2009, Markus Broecker <mbrckr@gmail.com>

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
 */
#include "Framebuffer.h"
#include "OpenGL.h"

using namespace glTools;


// combine the 3x3 combinations into the correct enum
static GLenum getInternalFormat(Framebuffer::Channels channels, Framebuffer::DataType type)
{
	switch(channels)
	{
		case Framebuffer::INTENSITY:
			if (type ==Framebuffer:: UNSIGNED_BYTE)
				return GL_INTENSITY;
			if (type == Framebuffer::HALF_FLOAT)
				return GL_INTENSITY16F_ARB;
			if (type == Framebuffer::FLOAT)
				return GL_INTENSITY32F_ARB;
				
		case Framebuffer::RGB:
			if (type == Framebuffer::UNSIGNED_BYTE)
				return GL_RGB;
			if (type == Framebuffer::HALF_FLOAT)
				return GL_RGB16F_ARB;
			if (type == Framebuffer::FLOAT)
				return GL_RGB32F_ARB;
		
		case Framebuffer::RGBA:
			if (type == Framebuffer::UNSIGNED_BYTE)
				return GL_RGBA;
			if (type == Framebuffer::HALF_FLOAT)
				return GL_RGBA16F_ARB;
			if (type == Framebuffer::FLOAT)
				return GL_RGBA32F_ARB;
	}
}

/// validates the framebuffer configuration
static void validate(unsigned int buffer) throw(std::string)
{
	glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, buffer );
	GLenum err = glCheckFramebufferStatusEXT( GL_FRAMEBUFFER_EXT );
	if (err != GL_FRAMEBUFFER_COMPLETE_EXT)
	{
		switch (err)
		{
			case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT:
				throw(std::string("Incomplete framebuffer"));
				break;
			case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT:
				throw(std::string("Wrong/incomplete size"));
				break;
			case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT:
				throw(std::string("Incomplete drawing buffers"));
				break;
			case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT:
				throw(std::string("Incomplete formats"));
				break;
			case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT:
				throw(std::string("Missing attachments"));
				break;
			case GL_FRAMEBUFFER_UNSUPPORTED_EXT:
				throw(std::string("Unsupported"));
				break;
			default:
				throw(std::string("Unknown error"));
		}
	}
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
}
	
Framebuffer::Framebuffer(unsigned int width, unsigned int height, Framebuffer::Channels channels, Framebuffer::DataType type, unsigned int colorbufferCount, Framebuffer::MinFilter filter) :
	mWidth(width), mHeight(height), mChannels(channels), mType(type), mFilter(filter), mColorbufferCount(colorbufferCount), mDepthRenderbuffer(0)
{	
	glGenFramebuffersEXT(1, &mBuffer);
	glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, mBuffer );

	mColorbuffer = new unsigned int[mColorbufferCount];
	GLenum internalFormat = getInternalFormat(channels, type);
	
	// create the color buffers
	glGenTextures( mColorbufferCount, mColorbuffer );
	for (unsigned int i = 0; i < mColorbufferCount; ++i)
	{		
		glBindTexture( GL_TEXTURE_2D, mColorbuffer[i] );
		glTexImage2D( GL_TEXTURE_2D, 0, internalFormat, mWidth, mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0 );
		
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); 
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		if (mFilter == LINEAR) 
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 
		else
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);

		//glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE );		
		glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + i, GL_TEXTURE_2D, mColorbuffer[i], 0);
	}
	

	// create the depth buffer
	glGenRenderbuffersEXT( 1, &mDepthRenderbuffer );
	glBindRenderbufferEXT( GL_RENDERBUFFER_EXT, mDepthRenderbuffer );
	glRenderbufferStorageEXT( GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24, mWidth, mHeight );
	glFramebufferRenderbufferEXT( GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, mDepthRenderbuffer );
	
	validate(mBuffer);
	glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, 0 );
}	

Framebuffer::~Framebuffer()
{
	glDeleteTextures( mColorbufferCount, mColorbuffer );
	delete[] mColorbuffer;
	
	glDeleteRenderbuffersEXT(1, &mDepthRenderbuffer);
	glDeleteFramebuffersEXT(1, &mBuffer);
	glError();
}

void Framebuffer::bind()
{
	glPushAttrib(GL_VIEWPORT_BIT);
	
	glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, mBuffer );
	glViewport(0, 0, mWidth, mHeight );
	
	if (mColorbufferCount > 1)
	{
		GLenum buffers[mColorbufferCount];
		for (unsigned int i = 0; i < mColorbufferCount; ++i)
			buffers[i] = GL_COLOR_ATTACHMENT0_EXT + i;
		
		glDrawBuffers(mColorbufferCount, buffers);
	}
	else
		glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
	
	glError();
}


void Framebuffer::disable()
{
	if (mFilter == MIPMAP)
	{
		for (int i = 0; i < mColorbufferCount; ++i)
		{
			glBindTexture(GL_TEXTURE_2D, mColorbuffer[i]);
			glGenerateMipmapEXT( GL_TEXTURE_2D );
		}
		glBindTexture(GL_TEXTURE_2D, 0);
	}
	
	glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, 0 );
	glDrawBuffer(GL_BACK);
	
	glPopAttrib();
	glError();
}	
	
Depthbuffer::Depthbuffer(unsigned int width, unsigned int height) : 
	mWidth(width), mHeight(height)
{
	// create the depth texture
	glGenTextures(1, &mDepthTexture);
	glBindTexture(GL_TEXTURE_2D, mDepthTexture);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

	glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, mWidth, mHeight, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, 0);
	glBindTexture(GL_TEXTURE_2D, 0);

	// create the fbo
	glGenFramebuffersEXT(1, &mBuffer);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mBuffer);

	glDrawBuffer(GL_NONE);
	glReadBuffer(GL_NONE);

	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, mDepthTexture, 0);
	
	validate(mBuffer);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
}

Depthbuffer::~Depthbuffer()
{
	glDeleteTextures(1, &mDepthTexture);
	glDeleteFramebuffersEXT(1, &mBuffer);
	glError();
}

void Depthbuffer::bind()
{
	glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, mBuffer );
	glDrawBuffer( GL_NONE );
	glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
	
	glPushAttrib(GL_VIEWPORT_BIT);
	glViewport(0, 0, mWidth, mHeight);
	glError();
}

void Depthbuffer::disable()
{
	glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, 0 );
	glDrawBuffer(GL_BACK);
	glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
	
	glPopAttrib();
	glError();
}

